package com.atguigu.day09;

import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.TableResult;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.descriptors.Csv;
import org.apache.flink.table.descriptors.FileSystem;
import org.apache.flink.table.descriptors.Schema;
import org.apache.flink.table.types.DataType;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.e;

public class Flink02_TableAPI_Connect_File {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //2.获取表的执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //TODO 3.获取文件中的数据映射到表中


        Schema schema = new Schema();
        schema.field("id", DataTypes.STRING());
        schema.field("ts",DataTypes.BIGINT());
        schema.field("vc",DataTypes.INT());

        tableEnv.connect(new FileSystem().path("input/sensor-sql.txt"))
                .withFormat(new Csv().fieldDelimiter(','))
                .withSchema(schema)
                .createTemporaryTable("sensor");


        //4.查询表里面的数据
        Table table = tableEnv.from("sensor");

//        Table resultTable = table.where($("id").isEqual("sensor_1"))
//                .select($("id"), $("ts"), $("vc"));

        Table resultTable = table.groupBy($("id"))
                .select($("id"), $("vc").sum());

        //5.将表转为流
//        DataStream<Row> result = tableEnv.toAppendStream(resultTable, Row.class);
//        result.print();



        //如果只是为了打印到控制台测试可以用以下方法
//        resultTable.execute().print();

//        TableResult tableResult = tableEnv.executeSql("select * from sensor");
        TableResult tableResult = tableEnv.executeSql("select * from "+table);
        tableResult.print();

//        env.execute();
    }


}
